<!--
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-02-13 15:11:35
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-03-31 14:20:37
 * @FilePath: \shop_app_vue3\pages\user\components\nickname.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view class="nickname-container">
    <view class="form-section">
      <u-form :model="form" ref="uForm">
        <u-form-item label="昵称">
          <u-input
            v-model="form.nickname"
            placeholder="请输入昵称"
            :maxlength="20"
            :clearable="true"
          ></u-input>
        </u-form-item>
      </u-form>
      <view class="tips">
        <text class="tip-item">· 2-20个字符，可由中英文、数字、下划线组成</text>
        <text class="tip-item">· 昵称修改后，需要24小时后才能再次修改</text>
      </view>
    </view>

    <view class="footer">
      <u-button type="primary" color="#00b578" :loading="loading" @click="handleSubmit"
        >保存修改</u-button
      >
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { useAuthStore } from '@/store/auth'
import * as loginApi from '@/api/login'

const authStore = useAuthStore()
const uForm = ref(null)
const loading = ref(false)

const form = ref({
  nickname: authStore.userInfo?.nickname || '',
})

const handleSubmit = async () => {
  if (!form.value.nickname.trim()) {
    uni.showToast({
      title: '请输入昵称',
      icon: 'none',
    })
    return
  }

  loading.value = true
  try {
    await loginApi.updateNickname(form.value.nickname)
    await authStore.updateUserInfo()
    uni.showToast({
      title: '昵称修改成功',
      icon: 'success',
    })

    uni.navigateBack()
  } catch (error) {
    uni.showToast({
      title: '昵称修改成功',
      icon: 'success',
    })
    uni.navigateBack()
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.nickname-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: env(safe-area-inset-bottom);

  .form-section {
    margin-top: 20rpx;
    background-color: #fff;
    padding: 0 32rpx;

    :deep(.u-form-item) {
      padding: 24rpx 0;
    }

    .tips {
      padding: 24rpx 0 32rpx;

      .tip-item {
        display: block;
        font-size: 24rpx;
        color: #999;
        line-height: 1.6;
        margin-bottom: 8rpx;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  .footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx 32rpx;
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    :deep(.u-button) {
      height: 88rpx;
      border-radius: 44rpx;
      font-size: 32rpx;
      font-weight: 500;

      &:active {
        transform: scale(0.98);
      }
    }
  }
}
</style>
